<template>
  <div>
    <a-card style="width: 480px" title="管理员登录">
      <a-form
        :model="formState"
        name="basic"
        autocomplete="off"
        ref="loginFormRef"
        @finish="onFinish"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名!' }]"
        >
          <a-input v-model:value="formState.username" placeholder="请输入用户名" />
        </a-form-item>

        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码!' }]"
        >
          <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item
          label="验证码"
          name="code"
          :rules="[{ required: true, message: '输入验证码' }]"
          style="height: 40px"
        >
          <a-input
            v-model:value="formState.code"
            placeholder="请输入验证码"
            style="width: 60%; height: 40px"
          />
          <a-image
            :width="100"
            style="height: 40px; margin-left: 16px; cursor: pointer"
            :preview="false"
            @click="init"
            :src="imgUrl"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 24 }">
          <a-flex justify="center" gap="middle" :vertical="true">
            <a-button type="primary" html-type="submit" block>登录</a-button>
            <a-button @click="handleReset" block>重置</a-button>
          </a-flex>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { login, verificationCode } from '@/apis/auth.js'

const router = useRouter()

const formState = ref({
  username: '',
  password: '',
  code: '',
  roles: '',
})

const imgUrl = ref()

const loginFormRef = ref()

const handleReset = () => {
  loginFormRef.value?.resetFields()
}

const onFinish = async (values) => {
  try {
    const { data = {}, code, msg } = await login({
      ...values,
      roles:"ROLE_ADMIN"
    })
    localStorage.setItem('token', data)
    localStorage.setItem('role', formState.value.roles)

    if (code === 200) {
        router.push('/manager')
        message.success('恭喜您，登录成功！')
        return
    } else {
      message.error(msg)
    }
  } catch (error) {
    console.log(error, 'user-login-error')
  }
}

const init = async () => {
  const { data = {} } = await verificationCode()
  imgUrl.value = data?.captcherImg
}

onMounted(() => {
  init()
})
</script>

<style lang="less" scoped></style>
